#include <QCoreApplication>
#include <QSettings>
#include <QDebug>
#include <QDataStream>
#include <QFile>

#define UNUSED(a) (void)(a)

int main(int argc, char *argv[])
{
    UNUSED(argc);
    UNUSED(argv);
    bool b_Success = false;
    unsigned int appSize = 0;
    QFile file("App.bin");
    if (!file.open(QIODevice::ReadOnly))
    {
        qDebug() << "open file failed";
        return 0;
    }
    appSize = file.size();

    QDataStream m_dataStream(&file);

    char *bindata = new char[appSize]{0};
    m_dataStream.readRawData(bindata,appSize);

    QSettings *config = new QSettings("config.ini", QSettings::IniFormat);
    for(QString con:config->allKeys())
    {
        int add = config->value(con).toString().toInt(&b_Success,16);
        //qDebug()<<con<<":"<<add;
        int times = 0;
        for(int index=0;;index++)
        {
            times = (unsigned char)bindata[add - 0x4000 +index]?0:times+1;
            //qDebug("%02x",(unsigned char)bindata[add - 0x4000 +index]);

            if(times >= 8)
            {
                QFile ofile(con.left(con.indexOf("/")));
                if (!ofile.open(QIODevice::WriteOnly))
                {
                    qDebug() <<con<< "open file failed";
                    break;
                }
                QDataStream outBin(&ofile);
                char startAdd[4] = {(char)((add>>24)&0xff),\
                                    (char)((add>>16)&0xff),(char)((add>>8)&0xff),(char)((add)&0xff)};
                outBin.writeRawData(startAdd,4);
                outBin.writeRawData(&bindata[add - 0x4000],index + 1);//
                ofile.close();
                break;
            }
        }

        QFile afile("Application.bin");
        if (!afile.open(QIODevice::WriteOnly))
        {
            qDebug() <<con<< "open file failed";
            break;
        }
        QDataStream outBin(&afile);
        char startAdd[4] = {0x00,0x00,0x40,0x00};
        outBin.writeRawData(startAdd,4);
        outBin.writeRawData(bindata,appSize);//
        file.close();
    }
    delete bindata;
}
